# -- encoding: utf-8 --

# Copyright 2010 István Szentandrási
# <etude-music-player@googlegroups.com>

# This file is part of Etude.
#
# Etude is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as 
# published by the Free Software Foundation, either version 3 
# of the License, or (at your option) any later version.
#
# Etude is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public License
# along with Etude. If not, see <http://www.gnu.org/licenses/>.

import xmmsclient
PB_PLAY = xmmsclient.PLAYBACK_STATUS_PLAY
PB_PAUSE = xmmsclient.PLAYBACK_STATUS_PAUSE
PB_STOP = xmmsclient.PLAYBACK_STATUS_STOP

from xmmsclient.xmmsapi import (MEDIALIB_ENTRY_STATUS_NEW, 
        MEDIALIB_ENTRY_STATUS_NOT_AVAILABLE, MEDIALIB_ENTRY_STATUS_OK, 
        MEDIALIB_ENTRY_STATUS_REHASH, MEDIALIB_ENTRY_STATUS_RESOLVING)

import time
import sys
import traceback

try:
    _
except:
    _ = lambda x: x

#globals
#define XMMS_MEDIALIB_ENTRY_PROPERTY_MIME "mime"
XMEP_ID = "id"
XMEP_URL = "url"
XMEP_ARTIST = "artist"
XMEP_ALBUM = "album"
XMEP_TITLE = "title"
XMEP_YEAR = "date"
XMEP_TRACKNR = "tracknr"
XMEP_GENRE = "genre"
XMEP_BITRATE = "bitrate"
XMEP_COMMENT = "comment"
XMEP_COMMENT_LANG = "commentlang"
XMEP_DURATION = "duration"
XMEP_CHANNEL = "channel"
XMEP_CHANNELS = "channels"
XMEP_SAMPLE_FMT = "sample_format"
XMEP_SAMPLERATE = "samplerate"
XMEP_LMOD = "lmod"
XMEP_GAIN_TRACK = "gain_track"
XMEP_GAIN_ALBUM = "gain_album"
XMEP_PEAK_TRACK = "peak_track"
XMEP_PEAK_ALBUM = "peak_album"
XMEP_COMPILATION = "compilation"
XMEP_ALBUM_ID = "album_id"
XMEP_ARTIST_ID = "artist_id"
XMEP_TRACK_ID = "track_id"
XMEP_ADDED = "added"
XMEP_BPM = "bpm"
XMEP_LASTSTARTED = "laststarted"
XMEP_SIZE = "size"
XMEP_IS_VBR = "isvbr"
XMEP_SUBTUNES = "subtunes"
XMEP_CHAIN = "chain"
XMEP_TIMESPLAYED = "timesplayed"
XMEP_PARTOFSET = "partofset"
XMEP_PICTURE_FRONT = "picture_front"
XMEP_PICTURE_FRONT_MIME = "picture_front_mime"
XMEP_STARTMS = "startms"
XMEP_STOPMS = "stopms"
XMEP_STATUS = "status"
XMEP_DESCRIPTION = "description"
XMEP_GROUPING = "grouping"
XMEP_PERFORMER = "performer"
XMEP_CONDUCTOR = "conductor"
XMEP_ARRANGER = "arranger"
XMEP_ORIGINAL_ARTIST = "original_artist"
XMEP_ALBUM_ARTIST = "album_artist"
XMEP_PUBLISHER = "publisher"
XMEP_COMPOSER = "composer"
XMEP_ASIN = "asin"
XMEP_COPYRIGHT = "copyright"
XMEP_WEBSITE_ARTIST = "website_artist"
XMEP_WEBSITE_FILE = "website_file"
XMEP_WEBSITE_PUBLISHER = "website_publisher"
XMEP_WEBSITE_COPYRIGHT = "website_copyright"

#so pygettext will automatically generate these
TRANSLATED_PROPS = (_("id"), 
        _("url"), 
        _("artist"),
        _("album"),
        _("title"),
        _("date"),
        _("tracknr"),
        _("genre"),
        _("bitrate"),
        _("comment"),
        _("commentlang"),
        _("duration"),
        _("channel"),
        _("channels"),
        _("sample_format"),
        _("samplerate"),
        _("lmod"),
        _("gain_track"),
        _("gain_album"),
        _("peak_track"),
        _("peak_album"),
        _("compilation"),
        _("album_id"),
        _("artist_id"),
        _("track_id"),
        _("added"),
        _("bpm"),
        _("laststarted"),
        _("size"),
        _("isvbr"),
        _("subtunes"),
        _("chain"),
        _("timesplayed"),
        _("partofset"),
        _("picture_front"),
        _("picture_front_mime"),
        _("startms"),
        _("stopms"),
        _("status"),
        _("description"),
        _("grouping"),
        _("performer"),
        _("conductor"),
        _("arranger"),
        _("original_artist"),
        _("album_artist"),
        _("publisher"),
        _("composer"),
        _("asin"),
        _("copyright"),
        _("website_artist"),
        _("website_file"),
        _("website_publisher"),
        _("website_copyright"))

#use this one for combos - not all properties are useful for that
PROP_SORT_SEARCH = ( 'url', 'artist', 'album', 'title', 'date', 'tracknr',
        'genre', 'bitrate', 'comment', 'duration', 'channel', 'added', 'bpm',
        'laststarted', 'size', 'timesplayed', 'description', 'performer',
        'original_artist', 'album_artist', 'composer', 'publisher')

(
        PLAYLIST_REPEAT_NONE,
        PLAYLIST_REPEAT_ONE,
        PLAYLIST_REPEAT_ALL
        ) = xrange(3)


def get_interval(num):
    """
    Format the number of seconds into a more readable format
    for example: get_interval(1234223234) >>> '1 month(s) 8 day(s) 47:14'
    """
    t = time.gmtime(num)
    d = ""
    if t.tm_mon > 1:
        d += "%i %s " % (t.tm_mon - 1, _("month(s)"))
    if t.tm_mday > 1 or t.tm_mon > 1:
        d += "%i %s " % (t.tm_mday - 1, _("day(s)"))
    if t.tm_hour > 0:
        d += "%i:" % t.tm_hour;
    d += time.strftime("%M:%S", t)
    return d

def decode_url(url_string):
    """
    as I couldn't find the function in the python api
    """
    url_iter = iter(url_string)
    ret_string = ''
    for c in url_iter:
        if c == '+':
            ret_string += ' '
        elif c == '%':
            try:
                ret_string += chr(long( ''.join( (url_iter.next(), url_iter.next()) ), 16) )
            except StopIteration:
                break
        else:
            ret_string += str(c)
    return ret_string

# ------- DECORATORS --------------

def check_result_error(emit = True):
    """
    just a decorator to check for errors in callback results
    lets say the second argument is the result
    """
    def _check_result_error(function):
        def __check_result_error(*args, **kw):
            if 'result' in kw:
                result = kw['result']
            elif len(args) >= 2: #for class methods
                result = args[1]
            else:
                result = None
            if result:
                if result.iserror():
                    if emit:
                        args[0].client.emit("e_result_error", result.value())
                        print("ERROR!: %s" % result.value())
                        traceback.print_stack()
                    else:
                        print("ERROR!: %s" % result.value())
                    return False
            return function(*args, **kw)
        return __check_result_error
    return _check_result_error

@check_result_error(True)
def check_cb(mycls, result = None):
    return False

def check_cb_None():
    """
    decorator for None callback
    check result error with the check_cb function
    """
    def _check_cb_None(function):
        def __check_cb_None(*args, **kw):
            try:
                if kw['cb'] == None:
                    kw['cb'] = lambda x: check_cb(args[0], result = x)
            except:
                kw['cb'] = lambda x: check_cb(args[0], result = x)
            return function(*args, **kw)
        return __check_cb_None
    return _check_cb_None



def check_fast(default_fast=False):
    """
    decorator to check if the fast connection should be used
    only for class members, which have self.client
    """
    def _check_fast(function):
        def __check_fast(*args, **kw):
            inst = args[0]
            fast = default_fast
            if 'fast' in kw:
                fast = kw['fast']
                del kw['fast']
            tmp = inst.client.xmms
            if fast == True:
                inst.client.xmms = inst.client.xmms_fast
            try:
                res = function(*args, **kw)
            finally:
                inst.client.xmms = tmp
            return res
        return __check_fast
    return _check_fast

def check_wait(default_wait=False):
    """
    decorator to check if function should wait(block)
    until the result is ready.
    only for class members, which have self.client
    """
    def _check_wait(function):
        def __check_wait(*args, **kw):
            wait = default_wait
            if 'wait' in kw:
                wait = kw['wait']
                del kw['wait']
            res = function(*args, **kw)
            if wait == True and hasattr(res, 'wait'):
                res.wait()
            return res
        return __check_wait
    return _check_wait

